/**
 * Created by jiexin on 2017/11/29.
 */
layui.use(['laydate', 'laypage', 'layer', 'laytpl', 'table', 'carousel', 'upload', 'form', 'element'], function() {
    var laydate = layui.laydate; //日期
    var laypage = layui.laypage;//分页
    var layer = layui.layer; //弹层
    var table = layui.table; //表格
    var $ = layui.jquery;
    var form = layui.form;
    var laytpl = layui.laytpl;
    var element = layui.element; //元素操作

    var inistatus = true;
    //规则变量

    console.log(aduit_on);

    if (rule_level === 1 || rule_level === 2){
        console.log(111111);
        colldbclick = function (mythis) {
            var $cit = $(mythis).parent();
            $cit.remove()
        };
        for (var n=0; n < item_data.length; n++) {
            $("#interest").append('<option value="'+ n + '">' + item_data[n] + '</option>');
            // console.log('<option value="'+ n + '">' + item_data[n] + '</option>')
        }
        form.render('select');
        if (rule_level === 2){
            $("#initiate_l").addClass('layui-hide');
            $("#initiate_t").removeClass('layui-hide');
            $(".ma-bottom-ops").addClass('layui-hide');
        }
    }else {
        $("#originator").attr('disabled', 'disabled');
        $("#initiate_l").addClass('layui-hide');
        $(".ma-bottom-ops").addClass('layui-hide');
        $("#equipment_sel_dev").addClass('layui-hide');
        if(rule_level === 3){
            $("#initiate_d").removeClass('layui-hide');
        }else if(rule_level === 4){
            $("#initiate_d").removeClass('layui-hide');
        }else if(rule_level === 5){
            //$("#initiate_b").removeClass('layui-hide');
            $("#initiate_d").removeClass('layui-hide');
        }else if(rule_level === 6){
            $("#initiate_c").removeClass('layui-hide');
        }
    }

    function showselect(lid, ldata, lname, lwork) {
        //当前操作判断
        var $rbj = $("#reviewerlist").find(".layui-unselect");
        $("#form_button").addClass('layui-hide');
        $("#originator").val(lname);
        $("#work_name").text(lwork);
        $("#originator").attr('disabled', 'disabled');
        for (var i=0; i < $rbj.length; i++){
            if (i < lid ){
                $($rbj[i]).addClass("layui-form-checked");
            }else {
                $($rbj[i]).removeClass("layui-form-checked");
            }
        }
        // $("#initiate_d").removeClass('layui-hide');
        $("#equipment_sel_dev").addClass('layui-hide');
        colldbclick = function (mythis) {};
        $("#view").empty();
        generateList(ldata);
        var $bma = $(".ma-bottom");
        $bma.css("top", "50%");
        $bma.css("height", "50%");
        $("#view").find(".layui-my-sel").attr('disabled', 'disabled');
    }


    function dealselect(lid, ldata, lname, lwork) {
        //当前操作判断
        var $rbj = $("#reviewerlist").find(".layui-unselect");
        $("#form_button").removeClass('layui-hide');
        $("#originator").val(lname);
        $("#work_name").text(lwork);
        $("#originator").attr('disabled', 'disabled');
        $("#initiate_l").addClass('layui-hide');
        for (var i=0; i < $rbj.length; i++){
            if (i < lid ){
                $($rbj[i]).addClass("layui-form-checked");
            }else {
                $($rbj[i]).removeClass("layui-form-checked");
            }
        }
        $("#view").empty();
        generateList(ldata);
        if (lid > 2){
            $("#equipment_sel_dev").addClass('layui-hide');
            $("#view").find(".layui-my-sel").attr('disabled', 'disabled');
            colldbclick = function (mythis) {};
        }else {
            colldbclick = function (mythis) {
                var $cit = $(mythis).parent();
                $cit.remove()
            };
            $("#initiate_t").removeClass('layui-hide');
            $("#equipment_sel_dev").removeClass('layui-hide');
            $("#view").find(".layui-my-sel").removeAttr('disabled', 'disabled');

        }
        var $bma = $(".ma-bottom");
        $bma.css("top", "50%");
        $bma.css("height", "50%");
    }

    copyText = function (mythis) {
        var $cit = $(mythis).parent();
        if ($cit.find(".layui-show")["length"] === 1 ){
            $cit.find(".layui-colla-content").removeClass("layui-show");
        } else{
            $cit.find(".layui-colla-content").addClass("layui-show");
        }
    };

    //流程发起div关闭事件
    $(".button-ma").on('click', function () {
        colldbclick = function (mythis) {
            var $cit = $(mythis).parent();
            $cit.remove()
        };
        $("#originator").removeAttr('disabled');
        $("#equipment_sel_dev").removeClass('layui-hide');
        $("#originator").val("");
        $("#form_button").removeClass('layui-hide');
        $("#work_name").text("产品经理");
        $("#view").empty();
        if (inistatus){
            var $bma = $(".ma-bottom");
            $bma.css("top", "50%");
            $bma.css("height", "50%");
            inistatus = false
        }
    });

    //流程发起div显示事件
    $(".button-down").on('click', function () {
        var $bma = $(".ma-bottom");
        $bma.css("top", "0");
        $bma.css("height", "100%");
        inistatus = true
    });

    //
    var getTpl = demo.innerHTML;
    function createList(ldata) {
        // var view = document.getElementById('view');
        for (var i = 0 ; i < ldata.length; i++){
            laytpl(getTpl).render(ldata[i], function(html){
                // view.innerHTML += html;
                $("#view").append(html)
            });
        }
    }
    function generateList(gdata) {
        for (var i = 0 ; i < gdata.length; i++){
            var idname = gdata[i]["title"];
            var addjson = {title: idname, ionename: idname+"__1", itwoname: idname+"__2", tonename: idname+"__3", ttwoname: idname+"__4"};
            laytpl(getTpl).render(addjson, function(html){
                // view.innerHTML += html;
                $("#view").append(html)
            });

            $.each(gdata[i], function (k,v) {
                if (k !== "title"){
                    $("#"+k).val(v)
                }
            })
        }
    }

    //项目添加
    $("#equipment_add").on('click', function () {
        var equipment_name = $("#equipment_sel").find(".layui-this").text();
       if (equipment_name !== ""){
           var eq_data = [{ //数据
                "title":equipment_name,
                "ionename":equipment_name+ "__1",
                "itwoname":equipment_name+ "__2",
                "tonename":equipment_name+ "__3",
                "ttwoname":equipment_name+ "__4"
            }];
           createList(eq_data)
       }
    });

    //项目列表点击事件
    // $(".layui-colla-title").on('click', function () {
    //     var $cit = $(this).parent();
    //     console.log(22222222222);
    //     if ($cit.find(".layui-show")["length"] === 1 ){
    //         $cit.find(".layui-colla-content").removeClass("layui-show");
    //     } else{
    //         $cit.find(".layui-colla-content").addClass("layui-show");
    //     }
    // });


    //添加点击
    form.on("submit(initiate_l)", function (ldata) {
        $("#project_t").trigger('click');
        var l_o_data = ldata.field["originator"];
        var addid = parseInt(rule_level) + 1;
        var return_data = {"originator":l_o_data,"item_list": JSON.stringify(pt_name_list), "item_describe": JSON.stringify(pt_data_list), "process": addid, "status":0};
        $.ajax({
            url:'/audit-add/',
            dataType: 'json',
            type:'POST',
            data:return_data,
            success: function (a_return_data) {
                // console.log(a_return_data,111111);
                $("#initiate_r").trigger('click');
                modtable();
            }
        })
    });

    //提交事件
    form.on("submit(initiate_t)", function (tdata) {
        $("#project_t").trigger('click');
        var addid = parseInt(rule_level) + 1;
        var t_return_data = {'id': deal_with_id,"item_list": JSON.stringify(pt_name_list), "item_describe": JSON.stringify(pt_data_list), "process": addid};
        $.ajax({
            url:'/audit-add-pro/',
            dataType: 'json',
            type:'POST',
            data:t_return_data,
            success: function (a_return_data) {
                // console.log(a_return_data,111111);
                if (a_return_data["status"] === 0){
                    layer.msg("提交成功！");
                    $(".button-down").trigger('click');
                    modtable();

                }
            }
        })
    });

    //通过事件
    form.on("submit(initiate_d)", function (ddata) {
        var addid = parseInt(rule_level) + 1;
        var d_return_data = {'id': deal_with_id, "process": addid};
        $.ajax({
            url:'/audit-through/',
            dataType: 'json',
            type:'POST',
            data:d_return_data,
            success: function (a_return_data) {
                if (a_return_data["status"] === 0){
                    layer.msg("已通过！");
                    $(".button-down").trigger('click');
                    modtable();

                }
            }
        })
    });

    //构建
    var jenkins_context = '<div><span>正在构建</span></div><div style="width:320px; height:100px; overflow: auto"><form id="form_jenkins" name="form_jenkins" class="layui-form layui-form-pane"><div class="layui-form-item"><div id="jenkins_div" class="layui-input-inline" style="width: 100%"></div></div><form></div>';
    function addjenkinsdiv(jdiv_list) {
        var $jbj = $("#jenkins_div");
        $jbj.empty();
        for (var j=0; j< jdiv_list.length; j++){
            var j_div = "";
            $.each(jdiv_list[j],function (k,v) {
                if (v[0] === "SUCCESS"){
                    j_div = '<div class="layui-unselect layui-form-checkbox layui-form-checked" lay-skin=""><span>'+ k + ':' + v[1] +'</span><i class="layui-icon"></i></div>'
                    $jbj.append(j_div)
                }else {
                    j_div = '<div class="layui-unselect layui-form-checkbox " lay-skin=""><span>'+ k +'</span><i class="layui-icon"></i></div>'
                    $jbj.append(j_div)
                }
            })
        }

    }


    $("#initiate_b").on("click", function () {
        layer.msg(
            content=jenkins_context,
            {
                time: 200000,
                area: ['370px', '200px'],
                //200s后自动关闭
                btn: ['取消'],
                success: function (layero) {
                    var btn = layero.find('.layui-layer-btn');
                    btn.addClass('layui-hide');
                    btn.addClass('layui-jenkins-button');
                    btn.css('text-align', 'center');
                    btn.on('click', function () {
                        $("#initiate_b").addClass('layui-hide');
                        $("#initiate_d").removeClass('layui-hide')
                    })
                }
            }
        );


        // $.ajax({
        //     url:"/audit-build/",
        //     dataType: "json",
        //     type: "POST",
        //     data: {"id":deal_with_id},
        //     success: function () {
        //
        //     }
        // })

        var b_post_data={"id":deal_with_id, "type":0};
        $(function () {
            (function longPolling() {
                $.ajax({
                    url: "/audit-build/",
                    data: b_post_data,
                    dataType: "json",
                    type: "POST",
                    timeout: 10000,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (textStatus === "timeout") { // 请求超时
                            console.log("超时");
                            b_post_data={"id":deal_with_id, "type":1};
                            longPolling(); // 递归调用
                        } else {
                            console.log("失败");
                            b_post_data={"id":deal_with_id, "type":1};
                            longPolling();
                        }
                    },
                    success: function (data, textStatus) {
                        if (textStatus === "success") { // 请求成功
                            console.log(data);
                            b_post_data={"id":deal_with_id, "type":1};
                            if (data["end"] === 1){
                                addjenkinsdiv(data["data"]);
                                $(".layui-jenkins-button").removeClass('layui-hide');
                                return false
                            }else if (data["end"] === 0) {
                                addjenkinsdiv(data["data"]);
                            }
                            longPolling();
                        }
                    }
                });
            })();
        });
    });


    //完成
    form.on("submit(initiate_c)", function (cdata) {
        var describe_data=cdata.field["describe"];
        var addid = parseInt(rule_level) + 1;
        var c_return_data = {'id': deal_with_id, "status": 1, "describe":describe_data};
        $.ajax({
            url:'/audit-through/',
            dataType: 'json',
            type:'POST',
            data:c_return_data,
            success: function (a_return_data) {
                if (a_return_data["status"] === 0){
                    layer.msg("成功！");
                    $(".button-down").trigger('click');
                    modtable();
                }
            }
        })
    });

    //项目list数据获取
    var pt_name_list;
    var pt_data_list;
    form.on("submit(project_t)", function (ptdata) {
        var pt_data = ptdata.field;
        console.log(pt_data);
        pt_name_list = [];
        pt_data_list = [];
        var pt_json = {};
        var n = 1;
        $.each(pt_data, function (k,v) {
            var k_list = k.split('__');
            if ($.inArray(k_list[0], pt_name_list) < 0){
                pt_name_list.push(k_list[0]);
                pt_json["title"] = k_list[0];
                pt_json[k] = v;
                n += 1;
            }else {
                if (n%4 === 0){
                    pt_json[k] = v;
                    n = 1;
                    pt_data_list.push(pt_json);
                    pt_json = {}
                }else {
                    n += 1;
                    pt_json[k] = v;
                }
            }
        });
    });

    //list清空
    $("#initiate_r").on("click", function () {
        $("#view").find(".layui-colla-item").remove()
    });





    //table
     var table_format_new = [[
         {field: 'originator', align: 'center', title: '发起人', width: '15%'}
         , {field: 'item_list', align: 'center', title: '模块列表', width: '40%'}
         , {field: 'rule_name', align: 'center', title: '当前角色', width: '15%'}
         , {field: 'createDate', align: 'center', title: '发起时间', width: '15%'}
         , {fixed: 'right',width: '20%', align: 'center',  title: '操作', toolbar: '#newDemo', templet: '#newDemo'}
    ]];

    $('#audit_table_new').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtablen(etaleid,tableid,aduit_my,table_format_new);
        newtool(toolid,tableid);
    });

    var newtable;
    function createtablen(etaleid,tableid,datas,table_format) {
        newtable = table.render({
            elem: etaleid,
            id: tableid,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    var deal_with_id;
    function newtool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            // var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            deal_with_id = data["id"];
            if (layEvent === 'deal_with') {
                if (rule_level === 5){
                    // $("#initiate_b").removeClass('layui-hide');
                    // $("#initiate_d").addClass('layui-hide');
                    $("#initiate_d").removeClass('layui-hide');
                }else if (rule_level === 6){
                    $("#describe_div").removeClass('layui-hide');
                }
                var json_data = JSON.parse(data["item_describe"]);
                dealselect(data["process"], json_data, data["originator"], data["rule_name"])
            }else if (layEvent === 'rejected'){
                createrejected()
            }else if (layEvent === 'rejectedcheck'){
                var name = rule_data[data["dismiss_role"]];
                var reason = data["dismiss_reason"];
                console.log(name,reason);
                checkrejected(name,reason)
            }else if (layEvent === 'invalid'){
                startinvalid()
            }
        });
    }

    //
    $('#audit_table_old').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtableo(etaleid,tableid,aduit_on,table_format_new);
        oldtool(toolid,tableid);
    });

    var oldtable;
    function createtableo(etaleid,tableid,datas,table_format) {
        oldtable = table.render({
            elem: etaleid,
            id: tableid,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }


    function oldtool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            // var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            deal_with_id = data["id"];
            if (layEvent === 'check') {
                if (rule_level === 6){
                    $("#describe_div").addClass('layui-hide');
                }
                var json_data = JSON.parse(data["item_describe"]);
                showselect(data["process"], json_data, data["originator"], data["rule_name"]);
                // console.log(data)
            }else if (layEvent === 'invalid'){
                startinvalid()
            }
        });
    }

    //驳回弹出层
    var rejected_content;
    function createrejected() {
        rejected_content ='<form id="createrejected" name="createrejected" class="layui-form layui-form-pane" style="color:#000"><div class="layui-form-item"><label class="layui-form-label" style="color:#000;">驳回选择</label><div class="layui-input-block"><select id="rejectedlist" name="rulelist" lay-filter="rulelist"><option value=""></option>';
        var end_context='</select></div></div><div class="layui-form-item layui-form-text"><label class="layui-form-label">驳回原因</label><div class="layui-input-block"><textarea id="rejectedwhy" name="rejectedwhy" placeholder="请输入内容" class="layui-textarea" style="resize:none"></textarea></div></div></form>';
        $.each(rule_data, function (k,v) {
            if (k < rule_level){
                rejected_content = rejected_content + '<option value="' + k + '" selected="">' + v + '</option>'
            }
        });
        rejected_content = rejected_content + end_context;
        layer.msg(
            content=rejected_content,
            {
            time: 200000,
            area: ['300px', '280px'],
            //200s后自动关闭
            btn: ['确定', '取消'],
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                var btntrue = layero.find('.layui-layer-btn0');
                form.render('select');
                btn.css('text-align', 'center');
                btntrue.on('click', function () {
                    var work_id = $("#rejectedlist").val();
                    var reason = $("#rejectedwhy").val();
                    var r_post_data = {"id":deal_with_id, "dismiss_role": rule_level, "dismiss_reason": reason, "process":work_id};
                    console.log(r_post_data);
                    $.ajax({
                        url:'/audit-through/',
                        dataType: 'json',
                        type:'POST',
                        data:r_post_data,
                        success: function (r_return_data) {
                            if (r_return_data["status"] === 0){
                                layer.msg("操作成功！");
                                $(".button-down").trigger('click');
                                modtable();
                            }
                        }
                    })
                })
            }
        });

    }

    // 驳回查看弹出层
    function checkrejected(cname, creason) {
        var end_context='<form id="checkrejected" name="checkrejected" class="layui-form layui-form-pane" style="color:#000"><div class="layui-form-item"><label class="layui-form-label">驳回人</label><div class="layui-input-inline"><input id="whyname" type="text" name="whyname" placeholder="请输入" autocomplete="off" class="layui-input" disabled></div></div><div class="layui-form-item layui-form-text"><label class="layui-form-label">驳回原因</label><div class="layui-input-block"><textarea id="whydata" name="whydata" placeholder="请输入内容" class="layui-textarea" style="resize:none" disabled></textarea></div></div></form>';
        layer.msg(
            content=end_context,
            {
            time: 200000,
            area: ['350px', '260px'],
            //200s后自动关闭
            btn: ['取消'],
            success: function (layero) {
                $("#whyname").val(cname);
                $("#whydata").val(creason);
                var btn = layero.find('.layui-layer-btn');
                btn.css('text-align', 'center');
            }
        });
    }

    //作废函数
    function startinvalid() {
        var s_data = {"id":deal_with_id, "is_delete":1};
        $.ajax({
            url:'/audit-through/',
            dataType: 'json',
            type:'POST',
            data:s_data,
            success: function (s_return_data) {
                if (s_return_data["status"] === 0){
                    layer.msg("成功作废！");
                    modtable();
                }
            }
        })
    }




    //定时获取table
    function modtable() {
        $.ajax({
            url:'/audit-obtain/',
            dataType:'JSON',
            type: 'POST',
            data: {"level":rule_level},
            success:function (m_return_data) {
                oldtable.reload({
                    data:m_return_data["aduit_on"]
                });
                newtable.reload({
                    data:m_return_data["aduit_my"]
                })
            }
        })
    }


    $('.demoTable .layui-btn').on('click',
        function() {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        }
    );
});